<template>
  <view class="order-list-page">
    <!-- 状态筛选 -->
    <view class="filter-tabs">
      <view 
        v-for="tab in tabs" 
        :key="tab.value" 
        :class="['tab-item', {active: activeTab === tab.value}]"
        @click="changeTab(tab.value)"
      >
        {{tab.label}}
      </view>
    </view>
    
    <!-- 订单列表 -->
    <scroll-view 
      scroll-y 
      class="order-scroll" 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      @refresherrefresh="refresh"
    >
      <view class="order-container">
        <view 
          v-for="order in orderList" 
          :key="order.id" 
          class="order-card"
          @click="navigateToDetail(order.id)"
        >
          <view class="order-header">
            <text class="order-no">订单号: {{order.pao_order}}</text>
            <text :class="['order-status', statusClass(order.status)]">
              {{getStatusText(order.status)}}
            </text>
          </view>
          
          <view class="order-content">
            <image 
              v-if="order.image" 
              :src="JSON.parse(order.image)[0].url" 
              class="order-image"
              mode="aspectFill"
            ></image>
            <view class="order-info">
              <text class="order-title">{{order.title}}</text>
              <text class="order-price">¥{{order.price}}</text>
              <text class="order-time">{{formatTime(order.create_time)}}</text>
            </view>
          </view>
          
          <view class="order-footer" v-if="showActions(order)">
            <button 
              v-if="order.status === 0" 
              class="mini-btn cancel-btn"
              @click.stop="cancelOrder(order.id)"
            >
              取消订单
            </button>
            <button 
              v-if="order.status === 1" 
              class="mini-btn confirm-btn"
              @click.stop="completeOrder(order.id)"
            >
              确认完成
            </button>
          </view>
        </view>
        
        <view class="load-more" v-if="loading">
          <text>加载中...</text>
        </view>
        <view class="no-more" v-if="noMore">
          <text>没有更多了</text>
        </view>
      </view>
    </scroll-view>
    
    <!-- 取消订单确认对话框 -->
    <uni-popup ref="cancelDialog" type="dialog">
      <uni-popup-dialog 
        type="warning"
        title="确认取消"
        :content="`确定要取消订单 ${currentOrderNo} 吗？`"
        @confirm="confirmCancel"
        @close="closeCancelDialog"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tabs: [
        { label: '全部', value: -1 },
        { label: '待接单', value: 0 },
        { label: '进行中', value: 1 },
        { label: '已完成', value: 2 },
        { label: '已取消', value: 3 }
      ],
      activeTab: -1,
      orderList: [],
      page: 1,
      pageSize: 10,
      loading: false,
      noMore: false,
      currentOrderId: null,
      currentOrderNo: '',
	  useMockData: true, // 设为 false 时使用真实接口数据
	  mockOrders: this.generateMockOrders(15)
    }
  },
  onShow() {
    this.refresh();
  },
  methods: {
    // 加载订单列表
    // 生成假数据的方法
        generateMockOrders(count) {
          const statusList = [0, 1, 2, 3]; // 0待接单 1进行中 2已完成 3已取消
          const typeList = ['快递代取', '外卖代买', '文件传递', '超市代购'];
          const mockImages = [
            [{url: '/static/mock/delivery.jpg'}],
            [{url: '/static/mock/food1.jpg'}, {url: '/static/mock/food2.jpg'}],
            [{url: '/static/mock/document.jpg'}],
            [{url: '/static/mock/shopping1.jpg'}, {url: '/static/mock/shopping2.jpg'}]
          ];
          
          const orders = [];
          const now = new Date();
          
          for (let i = 0; i < count; i++) {
            const status = statusList[Math.floor(Math.random() * statusList.length)];
            const typeIndex = Math.floor(Math.random() * typeList.length);
            const isPaid = status !== 0;
            
            orders.push({
              id: 1000 + i,
              pao_order: 'PO' + now.getTime() + i,
              user_id: 2000 + Math.floor(Math.random() * 10),
              create_time: new Date(now.getTime() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
              type: typeIndex + 1,
              title: `${typeList[typeIndex]}服务`,
              remark: `这是关于${typeList[typeIndex]}的详细描述，请尽快完成`,
              price: (Math.random() * 50 + 5).toFixed(2),
              status: status,
              contact: `138${Math.floor(10000000 + Math.random() * 90000000)}`,
              image: JSON.stringify(mockImages[typeIndex]),
              pay_time: isPaid ? new Date(now.getTime() - Math.random() * 3 * 24 * 60 * 60 * 1000).toISOString() : null,
              pay_type: isPaid ? (Math.floor(Math.random() * 2) === 0 ? 0 : 3) : null, // 0微信 3余额
              tk_time: status === 3 ? new Date(now.getTime() - Math.random() * 2 * 24 * 60 * 60 * 1000).toISOString() : null
            });
          }
          
          return orders;
        },
        
        // 修改后的加载订单方法
        async loadOrders() {
          if (this.loading || this.noMore) return;
          
          this.loading = true;
          
          if (this.useMockData) {
            // 使用假数据
            await new Promise(resolve => setTimeout(resolve, 800)); // 模拟网络延迟
            
            let filteredOrders = this.mockOrders;
            
            if (this.activeTab !== -1) {
              filteredOrders = this.mockOrders.filter(order => order.status === this.activeTab);
            }
            
            const start = (this.page - 1) * this.pageSize;
            const end = start + this.pageSize;
            const pageData = filteredOrders.slice(start, end);
            
            if (this.page === 1) {
              this.orderList = pageData;
            } else {
              this.orderList = [...this.orderList, ...pageData];
            }
            
            this.noMore = end >= filteredOrders.length;
            this.page++;
          } else {
            // 真实接口调用
            try {
              const params = {
                page: this.page,
                limit: this.pageSize
              };
              
              if (this.activeTab !== -1) {
                params.status = this.activeTab;
              }
              
              const res = await this.$http.get('/pao/list', { params });
              
              if (this.page === 1) {
                this.orderList = res.data.data;
              } else {
                this.orderList = [...this.orderList, ...res.data.data];
              }
              
              this.noMore = res.data.data.length < this.pageSize;
              this.page++;
            } catch (e) {
              console.error(e);
            }
          }
          
          this.loading = false;
        },
    
    // 切换标签
    changeTab(tab) {
      if (this.activeTab === tab) return;
      
      this.activeTab = tab;
      this.page = 1;
      this.noMore = false;
      this.loadOrders();
    },
    
    // 刷新数据
    refresh() {
      this.page = 1;
      this.noMore = false;
      this.loadOrders();
    },
    
    // 加载更多
    loadMore() {
      this.loadOrders();
    },
    
    // 格式化时间
    formatTime(time) {
      return time ? time.replace('T', ' ').substr(0, 16) : '--';
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待接单',
        1: '进行中',
        2: '已完成',
        3: '已取消',
        4: '其他'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 状态样式
    statusClass(status) {
      return `status-${status}`;
    },
    
    // 是否显示操作按钮
    showActions(order) {
      // 发布者可以取消待接单订单
      // 接单者可以确认完成
      return (order.status === 0 || order.status === 1);
    },
    
    // 跳转到详情页
    navigateToDetail(id) {
      uni.navigateTo({
        url: `/pagesA/errand-detail?id=${id}`
      });
    },
    
    // 取消订单
    cancelOrder(id) {
      const order = this.orderList.find(item => item.id === id);
      if (!order) return;
      
      this.currentOrderId = id;
      this.currentOrderNo = order.pao_order;
      this.$refs.cancelDialog.open();
    },
    
    // 确认取消订单
    async confirmCancel() {
      try {
        const res = await this.$http.post('/pao/cancel', {
          id: this.currentOrderId
        });
        
        if (res.code === 200) {
          uni.showToast({ title: '取消成功', icon: 'success' });
          this.refresh();
        } else {
          uni.showToast({ title: res.msg || '取消失败', icon: 'none' });
        }
      } catch (e) {
        uni.showToast({ title: '请求失败', icon: 'none' });
      } finally {
        this.closeCancelDialog();
      }
    },
    
    // 关闭取消对话框
    closeCancelDialog() {
      this.$refs.cancelDialog.close();
      this.currentOrderId = null;
      this.currentOrderNo = '';
    },
    
    // 确认完成订单
    async completeOrder(id) {
      uni.showModal({
        title: '确认完成',
        content: '确认任务已完成吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const result = await this.$http.post('/pao/complete', {
                id: id
              });
              
              if (result.code === 200) {
                uni.showToast({ title: '操作成功', icon: 'success' });
                this.refresh();
              } else {
                uni.showToast({ title: result.msg || '操作失败', icon: 'none' });
              }
            } catch (e) {
              uni.showToast({ title: '请求失败', icon: 'none' });
            }
          }
        }
      });
    }
  }
}
</script>

<style scoped>
.order-list-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.filter-tabs {
  display: flex;
  background-color: #fff;
  padding: 20rpx 0;
  position: sticky;
  top: 0;
  z-index: 10;
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  padding: 10rpx 0;
  position: relative;
}

.tab-item.active {
  color: #09bb07;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background-color: #09bb07;
  border-radius: 2rpx;
}

.order-scroll {
  flex: 1;
  height: calc(100vh - 100rpx);
}

.order-container {
  padding: 20rpx;
}

.order-card {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.order-no {
  font-size: 24rpx;
  color: #999;
}

.order-status {
  font-size: 26rpx;
}

.status-0 {
  color: #FF9900;
}

.status-1 {
  color: #09bb07;
}

.status-2 {
  color: #999;
}

.status-3 {
  color: #FF5A5F;
}

.status-4 {
  color: #666;
}

.order-content {
  display: flex;
  padding: 20rpx;
}

.order-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.order-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.order-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.order-price {
  font-size: 32rpx;
  color: #FF5A5F;
  font-weight: bold;
  margin: 10rpx 0;
}

.order-time {
  font-size: 24rpx;
  color: #999;
}

.order-footer {
  display: flex;
  justify-content: flex-end;
  padding: 0 20rpx 20rpx;
}

.mini-btn {
  font-size: 26rpx;
  padding: 8rpx 24rpx;
  border-radius: 40rpx;
  margin-left: 20rpx;
  line-height: 1.5;
}

.cancel-btn {
  background-color: #fff;
  color: #FF5A5F;
  border: 1rpx solid #FF5A5F;
}

.confirm-btn {
  background-color: #09bb07;
  color: #fff;
}

.load-more, .no-more {
  text-align: center;
  padding: 20rpx;
  font-size: 26rpx;
  color: #999;
}
</style>